package com.dmall.graph.floodfill;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 23:25
 */
public class Solution130 {

    private boolean[][] visited;
    private int R, C;
    private char[][] board;

    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public void solve(char[][] board) {
        this.board = board;
        R = board.length;
        C = board[0].length;
        this.visited = new boolean[R][C];

        for (int i = 0; i < C; i++) {
            dfs(0, i);
            dfs(R - 1, i);
        }

        for (int i = 1; i < R - 1; i++) {
            dfs(i, 0);
            dfs(i, C - 1);
        }

        for (int x = 1; x < R - 1; x++) {
            for (int y = 1; y < C - 1; y++) {
                if (!visited[x][y]) {
                    board[x][y] = 'X';
                }
            }
        }
    }

    private void dfs(int x, int y) {
        visited[x][y] = true;
        if (board[x][y] == 'O') {
            for (int d = 0; d < 4; d++) {
                int nextx = x + dirs[d][0];
                int nexty = y + dirs[d][1];
                if (inArea(nextx, nexty) && !visited[nextx][nexty] && board[nextx][nexty] == 'O') {
                    dfs(nextx, nexty);
                }
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }
}
